import sys, logging

from webob import exc
from wsgiref.simple_server import make_server
from formencode.validators import *

from authkit.permissions import UserIn
# from authkit.authorize import authorize, PermissionError

from clutch.decorators import expose, validate, transaction, authorize
import clutch.database
from clutch.controllers import clutch_stack, RegexController

logging.basicConfig(level=logging.INFO)

port = 8080
dburi = 'sqlite:///./devdata.sqlite'
clutch.database.init_sa(dburi)

from model import *

def main(args):
    eval(args[0])(args[1:])

def create(args):
    from elixir import create_all
    print 'Creating database....'
    drop_all()
    create_all()
    print 'Populating tables....'
    User(user_name=u'rick', password='foo')
    print 'done.'
    session.commit()
    
def shell(args):
    import IPython
    import model
    shell = IPython.Shell.IPShellEmbed(
        argv=args,
        banner='Using database at %s' % dburi,
        user_ns=model.__dict__)
    shell()

def serve(args):
    httpd = make_server('localhost', port, clutch_stack(root))
    print 'Serving on http://localhost:%s' % port
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print 'Shutting down...'

class Root(RegexController):

    @expose()
    def index(self):
        return 'Index page\n'

    @expose()
    def test(self, *remainder):
        return 'Test page %s\n' % '/'.join(remainder)

    @expose()
    def redir(self):
        raise exc.HTTPFound(location='/')

    @expose()
    @validate(validator=dict(title=UnicodeString()))
    def add_movie_ok(self, title=None):
        Movie(title=title)
        return 'Movie Created\n'

    @expose()
    @validate(validator=dict(title=UnicodeString()))
    def add_movie_err(self, title=None):
        Movie(title=title)
        assert False
        return 'Movie Created\n'

    @expose()
    @transaction(None)
    @authorize(UserIn(users=['rick']))
    def list_movies(self):
        return '\n'.join([ str(m) for m in Movie.query.all() ]) + '\n'

    @expose('json')
    @transaction(None)
    @authorize(UserIn(users=['rick']))
    def list_movies_json(self):
        return dict(movies=Movie.query().all())

    @expose()
    def create_db(self):
        from elixir import create_all
        create_all()
        return 'Database Created\n'

class DumpParams(RegexController):

    @expose()
    @validate(validator=dict(sku=Int(if_empty=555)))
    def index(self, **kw):
        return str(kw) + '\n'

root = Root((r'test1', DumpParams()),
            (r'test1/:name', DumpParams()),
            (r'test1/:name/\d*:sku', DumpParams()))

if __name__ == '__main__':
    main(sys.argv[1:])
